#缺点：慢； 要先将mp3等转换；
# pip install SpeechRecognition pydub langdetect
import re
import speech_recognition as sr
from langdetect import detect
import os
import tempfile
from pydub import AudioSegment

def convert_to_wav(audio_path):
    """将音频转换为适合ASR的16kHz单声道WAV格式"""
    if not os.path.exists(audio_path):
        raise FileNotFoundError(f"文件不存在: {audio_path}")
    
    if audio_path.lower().endswith('.wav'):
        return audio_path
    
    temp_wav = tempfile.NamedTemporaryFile(suffix='.wav', delete=False).name
    try:
        audio = AudioSegment.from_file(audio_path)
        audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
        audio.export(temp_wav, format="wav")
        return temp_wav
    except Exception as e:
        if os.path.exists(temp_wav):
            os.remove(temp_wav)
        raise Exception(f"音频转换失败: {e}")

def contains_chinese_chars(text):
    """判断文本中是否含有中文字符"""
    if not text:
        return False
    
    # Unicode汉字范围大致为：\u4e00-\u9fff
    chinese_pattern = re.compile(r'[\u4e00-\u9fff]')
    return bool(chinese_pattern.search(text))

def is_mostly_english(text):
    """判断文本是否主要由英文组成"""
    if not text:
        return False
    
    # 如果含有中文字符，直接判定为非英文
    if contains_chinese_chars(text):
        return False
    
    # 统计英文单词比例
    words = re.findall(r'\b\w+\b', text.lower())
    if not words:
        return False
    
    english_pattern = re.compile(r'^[a-z0-9\']+$')
    english_words = [w for w in words if english_pattern.match(w)]
    
    # 计算英文单词的比例
    ratio = len(english_words) / len(words)
    return ratio >= 0.8  # 80%以上为英文

def detect_audio_language_strict(audio_path):
    """
    严格语言检测：
    - 先尝试中文识别
    - 再尝试英文识别
    - 比较两种识别结果的可信度
    """
    recognizer = sr.Recognizer()
    wav_path = None
    
    try:
        wav_path = convert_to_wav(audio_path)
        
        with sr.AudioFile(wav_path) as source:
            recognizer.adjust_for_ambient_noise(source, duration=0.5)
            audio_data = recognizer.record(source)
            
            # 首先尝试中文识别
            try:
                chinese_text = recognizer.recognize_google(
                    audio_data,
                    language="zh-CN",  # 普通话
                    show_all=False
                )
                
                # 检查是否包含中文字符
                if contains_chinese_chars(chinese_text):
                    return "cn"
            except (sr.UnknownValueError, sr.RequestError):
                # 中文识别失败，继续尝试粤语
                try:
                    cantonese_text = recognizer.recognize_google(
                        audio_data,
                        language="zh-HK",  # 粤语/香港话
                        show_all=False
                    )
                    
                    if contains_chinese_chars(cantonese_text):
                        return "cn"
                except (sr.UnknownValueError, sr.RequestError):
                    pass
            
            # 尝试用英语识别
            try:
                english_text = recognizer.recognize_google(
                    audio_data,
                    language="en-US",
                    show_all=False
                )
                
                if is_mostly_english(english_text):
                    return "en"
            except (sr.UnknownValueError, sr.RequestError):
                pass
                
            # 默认返回中文，因为我们处理的主要是中文内容
            return "cn"
                
    except Exception as e:
        print(f"识别过程中出错: {e}")
        # 任何异常都返回中文（作为默认值）
        return "cn"
    finally:
        if wav_path and wav_path != audio_path and os.path.exists(wav_path):
            os.remove(wav_path)

if __name__ == "__main__":
    try:
        # audio_file = "input_files/粤语方言合成语音/d1tools.com-zh-HK-HiuGaai-20250625-094412.mp3"
        audio_file="input_files/英语语音/61-70968-0000.flac"
        result = detect_audio_language_strict(audio_file)
        print(f"检测到的语言: {result}")
    except Exception as e:
        print(f"错误: {e}")